package com.lagou.user.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lagou.entity.User;
import com.lagou.entity.UserDTO;
import com.lagou.entity.UserVO;
import com.lagou.user.UserService;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("user")
public class UserController {

    @Reference
    private UserService userService;

    //用户登录
    @GetMapping("login")
    public UserDTO login(String phone, String password) {

        UserDTO userDTO = new UserDTO ();
        User user = null;
        System.out.println ("phone:" + phone);
        System.out.println ("password" + password);
        //检测手机号是否注册
        Integer i = userService.checkPhone (phone);
        if (i == 0 ) {
            //未注册，自动注册
            userService.register (phone, password);
            userDTO.setMessage ("系统已自动注册，请记住密码");
            user = userService.login (phone, password);
        } else {
            user = userService.login (phone, password);
            if (user ==null) {
                userDTO.setState (300);
                userDTO.setMessage ("帐号密码不匹配，登录失败！");
            } else {
                userDTO.setState (200);
                userDTO.setMessage ("登录成功");
            }
        }
        userDTO.setContent (user);
        return userDTO;
    }

    @RequestMapping("updateUserInfo")
    public UserDTO updateUserInfo(@RequestBody UserVO userVO) {
        System.out.println ("用户id：" + userVO.getUserid ());
        System.out.println ("新头像地址：" + userVO.getPortrait ());
        System.out.println ("新昵称：" + userVO.getName ());

        UserDTO userDTO = new UserDTO ();
        if (userService.updateUserInfo (userVO.getUserid (),userVO.getPortrait (),userVO.getName ())==1) {
            userDTO.setState (200);
            userDTO.setMessage ("修改成功");
            userDTO.setSuccess (true);
            userDTO.setContent (userVO);
        } else {
            userDTO.setState (400);
            userDTO.setMessage ("修改失败");
            userDTO.setSuccess (false);
        }
        return userDTO;
    }

    /*修改用户密码
     * */
    @RequestMapping("updatePassword")
    public UserDTO updatePassword(@RequestBody UserVO userVO) {
        UserDTO userDTO = new UserDTO ();
        System.out.println ("用户id" + userVO.getUserid ());
        System.out.println ("新密码：" + userVO.getPassword ());
        if (userService.updatePassword (userVO.getUserid (),userVO.getPassword ()) ==1) {
            userDTO.setState (200);
            userDTO.setMessage ("修改成功");
            userDTO.setSuccess (true);
            userDTO.setContent (userVO);
        } else {
            userDTO.setState (400);
            userDTO.setMessage ("修改失败");
            userDTO.setSuccess (false);
        }
        return userDTO;
    }



    @PostMapping("upload")
    public UserDTO upload(MultipartHttpServletRequest request) throws Exception{

        //1.将文件保存到web服务器上
        //从页面请求中，获取上传的文件对象
        MultipartFile file = request.getFile ("fname");
        //从文件对象中获取文件的原始名称
        String oldFileName = file.getOriginalFilename ();
        //获取文件后缀
        String hou = oldFileName.substring (oldFileName.lastIndexOf (".") + 1);
        //为了避免文件重名，创建新文件名称
        String newFileName = (UUID.randomUUID ().toString () + "." + hou);
        //创建web服务器本地保存文件的目录（预先创建好文件d:upload,防止文件报错）
        File toSaveFile = new File ("d:/upload/" + newFileName);
        //将路径转换为文件
        file.transferTo (toSaveFile);
        //获取本地保存文件的目录的绝对路径
        String newFilePath = toSaveFile.getAbsolutePath ();

        //模拟网络延迟
        Thread.sleep (1000);

        /*2将文件上传到fastdfs服务器*/
        //加载配置文件
        ClientGlobal.initByProperties ("config/fastdfs-client.properties");
        //创建tracker客户端
        TrackerClient trackerClient = new TrackerClient ();
        // 通过tracker客户端获取tracker的连接服务并返回
        TrackerServer trackerServer = trackerClient.getConnection ();
        // 声明storage服务
        StorageServer storageServer = null;
        // 定义storage客户端
        StorageClient1  client = new StorageClient1 (trackerServer,storageServer);
        //定义元文件
        NameValuePair[] list = new NameValuePair[1];
        list[0] = new NameValuePair ("fileName",oldFileName);
        String fileId  = client.upload_file1 (newFilePath, hou, list);
        //关闭tracker服务
        trackerServer.close ();
        //封装userDTO数据
        UserDTO userDTO = new UserDTO ();
        userDTO.setState (200);
        userDTO.setMessage ("图片上传成功");
        userDTO.setSuccess (true);
        userDTO.setContent (fileId);
        System.out.println (userDTO.getState ());
        System.out.println (userDTO.getMessage ());
        System.out.println (userDTO.getSuccess ());
        return userDTO;
    }


}
